<template>
  <el-main>
    <el-form :model="ruleForm" enctype="multipart/form-data" multifile="multifile" ref="ruleForm" :rules="rules"
             label-width="100px" class="demo-ruleForm">
      <el-form-item label="楼盘名称" prop="name">
        <el-autocomplete
          class="inline-input"
          v-model="ruleForm.name"
          :fetch-suggestions="getPremisesInfoList"
          placeholder=""
          :trigger-on-focus="false"
          :popper-append-to-body="false"
          @select="handleSelect"
        >
        </el-autocomplete>
        <!--          <span @click="addPremises">找不到?店家添加新楼盘</span>-->
        <el-button type="warning" @click="addPremises">添加楼盘</el-button>
      </el-form-item>
      <el-form-item label="" prop="">
        <el-radio-group v-model="ruleForm.reserve1">
          <el-radio label="0" value="0">整租</el-radio>
          <el-radio label="1" value="1">合租</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="" prop="">
        <el-radio-group v-model="ruleForm.status">
          <el-radio label="1" value="1">已出租</el-radio>
          <el-radio label="0" value="1">未出租</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="楼栋号" prop="">
        <el-input v-model="ruleForm.buildingNo" placeholder="楼栋号"></el-input>
      </el-form-item>
      <el-form-item label="单元号" prop="">
        <el-input v-model="ruleForm.unitNo" placeholder="单元号"></el-input>
      </el-form-item>
      <el-form-item label="门牌号" prop="">
        <el-input v-model="ruleForm.roomNo" placeholder="门牌号"></el-input>
      </el-form-item>
      <el-form-item label="户型" prop="">
        <el-select v-model="ruleForm.room" placeholder="">
          <el-option label="1" value="1"></el-option>
          <el-option label="2" value="2"></el-option>
          <el-option label="3" value="3"></el-option>
          <el-option label="4" value="4"></el-option>
          <el-option label="5" value="5"></el-option>
          <el-option label="6" value="6"></el-option>
          <el-option label="7" value="7"></el-option>
          <el-option label="8" value="8"></el-option>
          <el-option label="9" value="9"></el-option>
        </el-select>
        室
        <el-select v-model="ruleForm.hall" placeholder="">
          <el-option label="0" value="0"></el-option>
          <el-option label="1" value="1"></el-option>
          <el-option label="2" value="2"></el-option>
        </el-select>
        厅
      </el-form-item>
      <el-form-item label="装修情况" prop="">
        <el-select v-model="ruleForm.decorate" placeholder="">
          <el-option label="精装" value="0"></el-option>
          <el-option label="简装" value="1"></el-option>
          <el-option label="毛坯" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="楼层" prop="floor">
        <el-input v-model="ruleForm.floor" placeholder="楼层"></el-input>
        共
        <el-input v-model="ruleForm.floorCount" placeholder="层"></el-input>
        层
      </el-form-item>
      <el-form-item label="设置管家" prop="">
        <el-select v-model="ruleForm.manager" placeholder="">
          <el-option v-for="item in this.userList" :label="item.userName" :value="item.userId"></el-option>
        </el-select>
        <span>您还可以在系统设置中添加其他管家</span>
      </el-form-item>
      <el-form-item label="房产面积" prop="">
        <el-input v-model="ruleForm.proportion" placeholder="房产面积"></el-input>
      </el-form-item>
      <span v-if="ruleForm.reserve1=='0' || ruleForm.reserve1==''">
        <el-form-item label="租金" prop="">
          <el-input placeholder="租金" v-model="ruleForm.roomInfoList[0].rental"></el-input>
        </el-form-item>
        </span>
      <el-form-item label="付款方式" prop="">
        押
        <el-select v-model="ruleForm.paymentMortgage" placeholder="">
          <el-option label="0" value="0"></el-option>
          <el-option label="1" value="1"></el-option>
          <el-option label="2" value="2"></el-option>
          <el-option label="3" value="3"></el-option>
        </el-select>
        付
        <el-select v-model="ruleForm.paymentPay" placeholder="">
          <el-option label="1" value="1"></el-option>
          <el-option label="2" value="2"></el-option>
          <el-option label="3" value="3"></el-option>
          <el-option label="4" value="4"></el-option>
          <el-option label="5" value="5"></el-option>
          <el-option label="6" value="6"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="公共配套" prop="">
        <el-checkbox-group v-model="ruleForm.publicFacilitys">
          <el-checkbox @change="getPublic(item.id)" v-for="item in this.publicList" :label="item.id" :value="item.id">
            {{ item.name }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <span v-if="ruleForm.reserve1=='0' || ruleForm.reserve1==''">
        <el-form-item label="房间配套" prop="">
          <el-checkbox-group v-model="ruleForm.roomInfoprivates">
            <el-checkbox @change="getPrivate(item.id)" v-for="item in this.privateList" :label="item.id"
                         :value="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        </span>
      <el-form-item label="房间区域图片">
        <el-upload
          action="#"
          ref="roomImage"
          :http-request="touploadfile1"
          :on-success="handleAvatarSuccess1"
          :before-upload="beforeAvatarUpload1" multiple>
          <el-button type="info">上传图片</el-button>
          <img v-if="this.ruleForm.roomImage" :src="this.ruleForm.roomImage" height="120px" width="120px">
        </el-upload>
      </el-form-item>
      <el-form-item label="公共区域图片">
        <el-upload
          action="#"
          ref="houseImage"
          :http-request="touploadfile2"
          :on-success="handleAvatarSuccess2"
          :before-upload="beforeAvatarUpload2" multiple>
          <el-button type="info">上传图片</el-button>
          <img v-if="this.ruleForm.houseImage" :src="this.ruleForm.houseImage" height="120px" width="120px">
        </el-upload>
      </el-form-item>
      <el-form-item label="房源介绍" prop="">
        <el-input type="textarea" v-model="ruleForm.introduce"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" @click="submitForm('ruleForm')">立即创建</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </el-main>
</template>

<script>
import {
  saveTbHouseInfo,
  sysUserList,
  tbPrivateFacilityList,
  tbPublicFacilityList,
  TbPremisesInfoList,
  uploadfile,
  getDistributedHouseIfOne
} from "@/api/housing/distributed";

export default {
  data() {
    return {
      ruleForm: {
        premisesId: '',
        name: '',
        reserve1: '0',
        type: '',
        status: '0',
        buildingNo: '',
        unitNo: '',
        roomNo: '',
        room: '',
        hall: '',
        decorate: '',
        floor: '',
        floorCount: '',
        manager: '',
        proportion: '',
        rental: '',
        paymentMortgage: '',
        paymentPay: '',
        introduce: '',

        publicFacility: '', //公共配套
        publicFacilitys: [],

        roomInfoprivates: [], //房间配套
        roomInfoprivate: '',

        roomInfoList: [{
          rental: '',
          status: 0,
          frontCover: '',
          roomImages: [],
          roomCode: '01',
          roomName: '',
        }],  //room房间对象

        houseImage: null,
        houseImages: [], //房子图片
        roomImage: null,
        roomImages: [],  //房间图片
      },
      //用于存储下拉框多选框的值
      userList: [],
      privateList: [],
      publicList: [],
      PremisesInfoList: {},
      houseImages: [],
      rules: {
        name: [
          {required: true, message: '请输入楼盘名称', trigger: 'blur'},
        ],
        floor: [
          {required: true, message: '请输入楼层', trigger: 'blur'},
        ],
        floorCount: [
          {required: true, message: '请输入楼层', trigger: 'blur'},
        ],
        room: [
          {required: true, message: '请输入楼层', trigger: 'blur'},
        ],
        hall: [
          {required: true, message: '请输入楼层', trigger: 'blur'},
        ],
        rental: [
          {required: true, message: '请输入租金', trigger: 'blur'},
        ],
        decorate: [
          {required: true, message: '请输入装修情况', trigger: 'blur'},
        ],
      }
    };
  },
  methods: {
    submitForm(formName) {
      console.log("输出p")
      for (var p in this.ruleForm.publicFacilitys) {
        this.ruleForm.publicFacility += "," + this.ruleForm.publicFacilitys[p];
      }
      this.ruleForm.publicFacility = this.ruleForm.publicFacility.substr(1);
      for (var r in this.ruleForm.roomInfoprivates) {
        this.ruleForm.roomInfoprivate += "," + this.ruleForm.roomInfoprivates[r];
      }
      this.ruleForm.roomInfoprivate = this.ruleForm.roomInfoprivate.substr(1);
      //room的name赋值
      this.ruleForm.roomInfoList[0].roomName = this.ruleForm.name + " " + this.ruleForm.room + "室 " + this.ruleForm.hall + "厅 " + this.ruleForm.roomInfoList[0].roomCode;
      this.ruleForm.roomInfoList[0].proportion = this.ruleForm.proportion;
      this.ruleForm.roomInfoList[0].floor = this.ruleForm.floor;
      console.log(this.ruleForm);
      saveTbHouseInfo(this.ruleForm).then(res => {
        console.log(res)
        if (res.flag) {
          this.$message.success("添加成功");
          this.ruleForm.houseImages = [];
          this.ruleForm.roomImage = [];
          this.ruleForm.roomInfoList.roomImages = [];
          this.ruleForm.roomInfoList.frontCover = [];
          //跳转房态图页面
          this.$router.push("/housing/roomrack");
        } else {
          this.$message.error("添加失败");
        }
      })
      // this.$refs[formName].validate((valid) => {
      //   if (valid) {
      //     alert('submit!');
      //   } else {
      //     console.log('error submit!!');
      //     return false;
      //   }
      // });
    },
    getPublic(id) {
      console.log(id);
      //this.ruleForm.publicFacility += ","+id;
    },
    getPrivate(id) {
      console.log(id);
      //this.ruleForm.roomInfoprivate += "," + id;
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    getUserList() {
      sysUserList().then(res => {
        console.log("输出user")

        this.userList = res.msgData;
        console.log(this.userList);
      })
    },
    getPrivateList() {
      tbPrivateFacilityList().then(res => {
        console.log("输出private");
        this.privateList = res.msgData;
        console.log(this.privateList);
      })
    },
    getPublicList() {
      tbPublicFacilityList().then(res => {
        console.log("输出public")
        this.publicList = res.msgData;
        console.log(this.publicList);
      })
    },
    //方法获取list
    getPremisesInfoList(name, callback) {
      TbPremisesInfoList(name).then(res => {
        console.log("输出根据楼盘名称获取到的值");
        //遍历msgData
        for (let msgDataKey of res.msgData) {
          //给传过来的msgData数据添加一个value值进行在下拉框展示
          //因为autocomplete只识别value字段并在下拉列中显示
          msgDataKey.value = msgDataKey.name + "(" + msgDataKey.provinceName + msgDataKey.cityName + msgDataKey.address + msgDataKey.name + ")";
        }
        console.log(res.msgData);
        //将加过值的msgData给我要展示的list
        this.PremisesInfoList = res.msgData;
        let data = {};
        data.id = "addPremises";
        data.value = "找不到?点击添加新楼盘";
        data.name = name;
        this.PremisesInfoList.push(data);
        //this.PremisesInfoList[PremisesInfoList.length].value = "<span>哈哈哈</span>";
        //callback 回调函数 将处理好的数据推回
        callback(this.PremisesInfoList);
      }).catch((error) => {
        console.log(error);
      });
    },
    //是选中某一列触发的事件,在这里item为选中字段所在的对象
    handleSelect(item) {
      console.log("输出----下拉数据")
      console.log(item);
      if (item.id == "addPremises") {
        this.$router.push({path: "/building/addhouse", query: {name: item.name}});
      } else {
        this.ruleForm.premisesId = item.id;
      }
      //this.ruleForm.roomInfoList.roomName = item.name;
    },
    //添加楼盘 跳转
    addPremises() {
      //改成添加楼盘的
      let name = this.ruleForm.name;
      this.$router.push({path: "/building/addhouse", query: {name: name}});
    },
    handleAvatarSuccess1(res, file) {
      console.log("成功1")
      console.log(res, file);
    },
    beforeAvatarUpload1(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    touploadfile1(fileObj) {
      console.log("我是图片上传1");
      console.log(fileObj);
      var formData = new FormData()
      formData.append('file', fileObj.file)
      uploadfile(formData, fileObj).then(res => {
        //console.log("图片上传", res, fileObj)
        fileObj.onSuccess(res.imgUrl)   // 接口返回成功时处理，调用onSuccess
        console.log(res);
        this.ruleForm.roomImage = res.msgData;
        this.ruleForm.roomImages.push(this.ruleForm.roomImage);
        this.ruleForm.roomInfoList[0].roomImages.push(this.ruleForm.roomImage);
      })
    },
    handleAvatarSuccess2(res, file) {
      console.log("成功2")
      console.log(res, file);

    },
    beforeAvatarUpload2(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    touploadfile2(fileObj) {
      console.log("我是图片上传2");
      console.log(fileObj);
      var formData = new FormData()
      formData.append('file', fileObj.file)
      uploadfile(formData, fileObj).then(res => {
        //console.log("图片上传", res, fileObj)
        fileObj.onSuccess(res.imgUrl)   // 接口返回成功时处理，调用onSuccess
        console.log(res);
        this.ruleForm.houseImage = res.msgData;
        this.ruleForm.houseImages.push(this.ruleForm.houseImage);
        this.ruleForm.roomInfoList[0].frontCover = this.ruleForm.houseImage;
      })
    },
    //根据houseId获取分散式房源
    distributedHouseIfOne(houseId, premisesName) {
      getDistributedHouseIfOne(houseId, premisesName).then(res => {
        console.log("输出修改回显的数据");
        console.log(res.msgData);
        //this.ruleForm = res.msgData;
        this.ruleForm.name = res.msgData.premisesName;
        this.ruleForm.premisesId = res.msgData.premisesId;

        this.ruleForm.reserve1 = res.msgData.reserve1 + '';
        this.ruleForm.status = res.msgData.status + '';

        this.ruleForm.buildingNo = res.msgData.buildingNo;
        this.ruleForm.unitNo = res.msgData.unitNo;
        this.ruleForm.roomNo = res.msgData.roomNo;
        this.ruleForm.room = res.msgData.room;
        this.ruleForm.hall = res.msgData.hall;
        this.ruleForm.decorate = res.msgData.decorate;
        this.ruleForm.floor = res.msgData.floor;
        this.ruleForm.floorCount = res.msgData.floorCount;
        this.ruleForm.manager = res.msgData.manager;
        this.ruleForm.proportion = res.msgData.proportion;
        this.ruleForm.roomInfoList[0].rental = res.msgData.roomInfoList[0].rental;
        this.ruleForm.paymentMortgage = res.msgData.paymentMortgage;
        this.ruleForm.paymentPay = res.msgData.paymentPay;
        this.ruleForm.introduce = res.msgData.introduce;
        this.ruleForm.houseImage = res.msgData.houseImages[0];
        this.ruleForm.roomImage = res.msgData.roomInfoList[0].frontCover;
      })
    }
  },
  created() {
    this.getUserList();
    this.getPrivateList();
    this.getPublicList();
    console.log("输出传来的row");
    let parse;
    if(this.$route.query.rowInfo!=undefined){
      parse = JSON.parse(this.$route.query.rowInfo);
    }
    console.log(parse);
    if (parse) {
      this.ruleForm.publicFacilitys = parse.publicFacility.split(",").map(Number);
      this.ruleForm.roomInfoprivates = parse.publicFacility.split(",").map(Number);
    }
    if (this.$route.query.houseId != null && this.$route.query.premisesName != null) {
      console.log("我是路径带参数" + this.$route.query.houseId + this.$route.query.premisesName);
      //根据houseId去后天获取数据进行回显
      this.distributedHouseIfOne(this.$route.query.houseId, this.$route.query.premisesName);
    } else {
      console.log("我是路径不带参数" + this.$route.query.houseId + this.$route.query.premisesName);
    }
  }
}
</script>

<style>
.el-autocomplete-suggestion {
  width: auto !important;
}
</style>
